package com.wenhao.queue;

import org.junit.jupiter.api.Test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 *
 * add remove 抛异常
 * offer poll 返回true或false
 * put take 阻塞
 * offer poll 设置超时时间
 *
 * @author Wenhao Tong
 * @create 2021-08-20 13:11
 */
public class BlockingQueueDemo {
    public static void main(String[] args) {
        BlockingQueue<String> msg = new ArrayBlockingQueue<>(3);
    }
    /**
     * 抛出异常
     */
    @Test
    public void test1 () {
        BlockingQueue<String> msg = new ArrayBlockingQueue<>(3);
        msg.add("1");
        msg.add("2");
        msg.add("3");
        // java.lang.IllegalStateException: Queue full
//        msg.add("4");

        // 删除
        msg.remove();
    }

    /**
     * 返回true / false
     */
    @Test
    public void test2() {
        BlockingQueue<String> msg = new ArrayBlockingQueue<>(3);
        msg.offer("1");
        msg.offer("2");
        msg.offer("3");
        msg.offer("4");

        System.out.println(msg.poll());
        System.out.println(msg.poll());

        // 检测队首元素
        System.out.println(msg.peek());
        System.out.println(msg.element());
        System.out.println(msg.poll());
    }

    /**
     * 等待 阻塞
     */
    @Test
    public void test3() throws InterruptedException {
        BlockingQueue<String> msg = new ArrayBlockingQueue<>(3);
        msg.put("1");
        msg.put("1");
        msg.put("1");
        // 一直阻塞
//        msg.put("1");
        System.out.println(msg.take());
        System.out.println(msg.take());
        System.out.println(msg.take());
        System.out.println(msg.take());

    }

    /**
     * 等待 超时
     */
    @Test
    public void test4() throws InterruptedException {
        BlockingQueue<String> msg = new ArrayBlockingQueue<>(3);
        msg.offer("1");
        msg.offer("2");
        msg.offer("3");
        msg.offer("4", 2,TimeUnit.SECONDS);

        System.out.println(msg.poll());
        System.out.println(msg.poll());

        // 检测队首元素
        System.out.println(msg.peek());
        System.out.println(msg.element());
        System.out.println(msg.poll());
    }
}
